package com.metro.activation.app.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.metro.activation.biz.beans.vo.BizClient;
import com.metro.activation.biz.beans.vo.BizPadManagement;
import com.metro.activation.biz.service.inf.IBizClientService;
import com.metro.activation.biz.service.inf.IBizPadManagementService;
import com.metro.activation.common.beans.MyResultCode;
import com.metro.activation.common.utils.DateUtil;
import com.metro.activation.common.utils.PropertiesUtil;
import com.metro.activation.web.controller.BaseController;
import com.metro.core.vo.JsonResult;
import com.metro.core.vo.ResultCode;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

@Api(value="NDS盒子",tags = {"NDS盒子激活API"})
@Controller
@RequestMapping(value = "/app")
public class ApiController extends BaseController{
	
	@Autowired
    private IBizClientService bizclientService;
	
	@Autowired
	private IBizPadManagementService bizPadManagementService;
	
	/**
	 * 读取配置
	 * @return
	 */
	@ApiOperation(value="读取配置", notes="")
	@ApiImplicitParams({
		
	})
	@RequestMapping(value = "client/config", method=RequestMethod.GET)
	@ResponseBody
	public JsonResult readConfig(HttpServletRequest request, HttpServletResponse response){
		JsonResult jr = new JsonResult();
		try{
			Properties properties = PropertiesUtil.getProperties("properties/client-config.properties");
			//公正服务器地址
			String justiceServer = properties.getProperty("justice.server");
			jr.setResult(ResultCode.SUCCESS);
			Map<String, Object> result = new HashMap<String, Object>();
			result.put("justiceServer", justiceServer);
			result.put("currentTime", DateUtil.getCurrentDateTime());
			jr.setData(result);
			jr.setResult(ResultCode.SUCCESS);
		}catch (Exception ex) {
			log.error("客户端激活出错",ex);
            jr.setResult(ResultCode.ERROR);
		}
		return jr;
	}
	
	/**
	 * 客户端激活
	 * @param request
	 * @param response
	 * @return
	 */
	@ApiOperation(value="客户端激活", notes="")
	@ApiImplicitParams({
		@ApiImplicitParam(name="activationCode",value="激活码",paramType="query",dataType="String",required=true),
		@ApiImplicitParam(name="customerName",value="客户名称",paramType="query",dataType="String",required=true),
		@ApiImplicitParam(name="clientId",value="客户端编号",paramType="query",dataType="String",required=true)
	})
	@RequestMapping(value = "client/active", method=RequestMethod.POST)
	@ResponseBody
	public JsonResult active(HttpServletRequest request, HttpServletResponse response){
		JsonResult jr = new JsonResult();
		try{
			String activationCode = request.getParameter("activationCode");//激活码
			String customerName = request.getParameter("customerName");//客户名称
			String clientId = request.getParameter("clientId");//客户端编号
			log.debug("");
			if(StringUtils.isBlank(activationCode)){
				jr.setResult(MyResultCode.ACTIVATION_CODE_IS_NULL);
				return jr;
			}
			if(StringUtils.isBlank(customerName)){
				jr.setResult(MyResultCode.CUSTOMERNAME_IS_NULL);
				return jr;
			}
			if(StringUtils.isBlank(clientId)){
				jr.setResult(MyResultCode.CLIENTID_IS_NULL);
				return jr;
			}
			//验证激活码是否已经被使用
			BizClient client = new BizClient();
			client.setActivationCode(activationCode);
			List<BizClient> clientList = bizclientService.queryForList(client);
			if(clientList.size() == 0){ // 未找到激活码
				jr.setResult(MyResultCode.ACTIVATION_CODE_NOT_EXIT);
				return jr;
			}
			BizClient queryClient = clientList.get(0);
			// 找到激活码并且已经被激活了
			if(queryClient.getClientId() != null){
				if(queryClient.getActivationStatus().equals("3") || queryClient.getActivationStatus().equals("2")){ 
					jr.setResult(MyResultCode.ACTIVATION_CODE_USED);
					return jr;
				}
			}
			//激活码未激活,可正常激活
			if(queryClient.getActivationStatus().equals("1")){  
				Date now = new Date();
				queryClient.setCustomerName(customerName);
				queryClient.setClientId(clientId);
				queryClient.setActivationTime(now);
				queryClient.setActivationStatus("3");//设置已激活
				queryClient.setLastUserTime(now);
				bizclientService.update(queryClient);
				jr.setResult(ResultCode.SUCCESS);
			}
		}catch(Exception ex){
			log.error("客户端激活出错",ex);
            jr.setResult(ResultCode.ERROR);
		}
		return jr;
	}
	
	/**
	 * 客户端自检
	 * @param request
	 * @param response
	 * @return
	 */
	@ApiOperation(value="客户端自检", notes="")
	@ApiImplicitParams({
		@ApiImplicitParam(name="clientId",value="客户端编号",paramType="query",dataType="String",required=true)
	})
	@RequestMapping(value = "client/check", method=RequestMethod.GET)
	@ResponseBody
	public JsonResult clientCheck(HttpServletRequest request, HttpServletResponse response){
		JsonResult jr = new JsonResult();
		try{
			String clientId = request.getParameter("clientId");
			if(StringUtils.isBlank(clientId)){
				jr.setResult(MyResultCode.CLIENTID_IS_NULL);
				return jr;
			}
			BizClient client = new BizClient();
			client.setClientId(clientId);
			BizClient oldClient = bizclientService.getLastByClientId(clientId);
			if(oldClient == null){
				jr.setResult(MyResultCode.CLIENT_IS_NULL); // 客户端不存在
				return jr;
			}
			if(oldClient.getActivationStatus().equals("2")){  //已注销状态
				jr.setResult(MyResultCode.ACTIVATION_CODE_IS_CANCEL);
				return jr;
			}
			if(oldClient.getActivationStatus().equals("3")){ // 已激活状态
				oldClient.setLastUserTime(new Date());
				bizclientService.update(oldClient);
				jr.setResult(ResultCode.SUCCESS);
			}
		}catch (Exception ex) {
			log.error("客户端自检出错", ex);
            jr.setResult(ResultCode.ERROR);
		}
		return jr;
	} 
	
	/**
	 * PAD绑定
	 * @return
	 */
	@ApiOperation(value="PAD绑定", notes="")
	@ApiImplicitParams({
		@ApiImplicitParam(name="deviceId",value="PAD编号",paramType="query",dataType="String",required=true),
		@ApiImplicitParam(name="clientId",value="客户端编号",paramType="query",dataType="String",required=true),
		@ApiImplicitParam(name="certNumber",value="证书编号",paramType="query",dataType="String",required=true),
		@ApiImplicitParam(name="deviceStatus",value="PAD状态",paramType="query",dataType="String",required=true)
	})
	@RequestMapping(value = "pad/bind", method=RequestMethod.POST)
	@ResponseBody
	public JsonResult padBind(HttpServletRequest request, HttpServletResponse response){
		JsonResult jr = new JsonResult();
		try{
			String deviceId = request.getParameter("deviceId"); // pad编号
			String clientId = request.getParameter("clientId"); // 客户端编号
			String certNumber = request.getParameter("certNumber");//证书编号
			String deviceStatus = request.getParameter("deviceStatus"); //pad状态
			
			BizPadManagement pad = new BizPadManagement();
			pad.setDeviceId(deviceId);
			List<BizPadManagement> padList = bizPadManagementService.queryForList(pad);
			//TODO pad状态为绑定状态，在数据库中没有记录，则为无效设备
			if(StringUtils.isBlank(deviceStatus)){  // 状态为空
				if(padList.size() > 0){ // 如果pad已经存在
					BizPadManagement old = padList.get(0);
					if(old.getStatus().equals("2")){//注销
						jr.setResult(MyResultCode.PAD_STATUS_CANCEL);
						return jr;
					}
					old.setLastUserTime(new Date());
					old.setUseClientId(clientId);
					old.setCertNumber(certNumber);
					bizPadManagementService.update(old);
					jr.setResult(ResultCode.SUCCESS);
					return jr;
				}
				pad.setFirstClientId(clientId);
				pad.setCertNumber(certNumber);
				pad.setLastUserTime(new Date());
				pad.setBindTime(new Date());
				pad.setUseClientId(clientId);
				pad.setStatus("1");
				bizPadManagementService.save(pad);
				jr.setResult(ResultCode.SUCCESS);
				return jr;
			}
			if(deviceStatus.equals("1")){// pad绑定状态
				if(padList.size() == 0){ // 没有pad记录则为无效设备
					jr.setResult(MyResultCode.PAD_IS_NULL);
					return jr;
				}else{ // 存在pad记录
					//判断状态
					BizPadManagement old = padList.get(0);
					if(old.getStatus().equals("2")){//注销
						jr.setResult(MyResultCode.PAD_STATUS_CANCEL);
						return jr;
					}
					old.setLastUserTime(new Date());
					old.setUseClientId(clientId);
					old.setCertNumber(certNumber);
					bizPadManagementService.update(old);
					jr.setResult(ResultCode.SUCCESS);
					return jr;
				}
			}
			if(deviceStatus.equals("0")){//pad为未绑定状态
				if(padList.size() >= 0){
					BizPadManagement old = padList.get(0);
					old.setCertNumber(certNumber);
					old.setLastUserTime(new Date());
//					old.setBindTime(new Date());
					old.setUseClientId(clientId);
					old.setStatus("1");
					bizPadManagementService.update(old);
					return jr;
				}else{
					pad.setFirstClientId(clientId);
					pad.setCertNumber(certNumber);
					pad.setLastUserTime(new Date());
					pad.setBindTime(new Date());
					pad.setUseClientId(clientId);
					pad.setStatus("1");
					bizPadManagementService.save(pad);
					jr.setResult(ResultCode.SUCCESS);
					return jr;
				}
			}
		}catch(Exception ex){
			log.error("PAD绑定出错",ex);
            jr.setResult(ResultCode.ERROR);
		}
		return jr;
	}
}
